package net.sevear.chaos.recommend
{
	import com.adobe.serialization.json.JSON;
	
	import flash.events.EventDispatcher;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	
	import mx.events.Request;
	
	import net.sevear.chaos.download.Predef;
	import net.sevear.chaos.event.ChaosErrorEvent;
	import net.sevear.chaos.event.authenticate.LoginEvent;
	import net.sevear.chaos.utils.Logger;
	import net.sevear.chaos.view.ChaosAlertPanel;
	import net.sevear.chaos.view.ChaosLogPanel;
	import net.sevear.chaos.vo.UserInfo;

	public class ChaosAuthenticater extends EventDispatcher
	{
		private static const LOGIN_URL:String = "/login";
		
		private var request:ChaosRemoteRequest;
		public function ChaosAuthenticater()
		{
			request = new ChaosRemoteRequest(3);
			request.addEventListener(ChaosErrorEvent.CHAOS_ERR,onErr);
		}
		
		public function register(uid:int,
								 uidAlias:String,
								 url:String,
								 name:String,
								 imgUrl:String,
								 version:String):void{
			var rst:URLRequest = new URLRequest(encodeURI(Predef.CHAOS_HOST+LOGIN_URL));
			rst.method = URLRequestMethod.POST;
			var vars:URLVariables = new URLVariables();
			var user:Object = new Object();
			user.uid = uid;
			user.alias = uidAlias;
			user.name = name;
			user.url = url;
			user.headimg = imgUrl;
			user.version = version;
			vars.userinfo = JSON.encode(user);
			vars.version = version;
			rst.data = vars;
			request.sendRequest(rst,onRegister);
		}
		
		private function onRegister(rst:Object):void{
			var ev:LoginEvent = new LoginEvent(LoginEvent.REGIST_SUCCESSFUL);
			dispatchEvent(ev);
		}
		
		private function onErr(e:ChaosErrorEvent):void{
			Logger.getInstance().logError(e.type,e.msg);
			ChaosLogPanel.getInstance().addBasicInfo(e.msg);
			var ev:LoginEvent = new LoginEvent(LoginEvent.REGIST_FAILED);
			dispatchEvent(ev);
		}
	}
}